package com.na.game.engine.widget.impl;

import android.graphics.Rect;
import android.graphics.Typeface;

import com.na.game.engine.graphics.Graphics;
import com.na.game.engine.graphics.Image;
import com.na.game.engine.util.GameConfig;
import com.na.game.engine.widget.Layout;
import com.na.game.engine.widget.Widget;

public class TimerLabel extends Widget {

	private Image background, bar;
	private int timeLimit; // ms
	private int remain;
	private int textSize;
	private Typeface typeface;
	
	public TimerLabel(Image background, Image bar, int timeLimit) {
		this(background, bar, timeLimit, GameConfig.FONT_DEFAULT_SIZE, null);
	}
	
	public TimerLabel(Image background, Image bar, int timeLimit, int textSize) {
		this(background, bar, timeLimit, textSize, null);
	}
	
	public TimerLabel(Image background, Image bar, int timeLimit, int textSize, Typeface typeface) {
		this.background = background;
		this.bar = bar;
		this.timeLimit = timeLimit;
		this.remain = timeLimit;
		this.textSize = textSize;
		this.typeface = typeface;
	}
	
	public void setTypeface(Typeface typeface) {
		this.typeface = typeface;
	}
	
	public void setTextSize(int textSize) {
		this.textSize = textSize;
	}

	@Override
	protected void paintImpl(Graphics g) {
		Rect rect = absBound;
		g.drawImage(background, rect.left, rect.top + (rect.height() - background.getHeight()) / 2, Layout.TOP_LEFT);
		int w = (int) ((float) remain / timeLimit * rect.width());
		g.setClip(rect.left, rect.top, w, rect.height());
		g.drawImage(bar, rect.left, rect.top + (rect.height() - bar.getHeight()) / 2, Layout.TOP_LEFT);
		g.setClip(rect.left, rect.top, rect.width(), rect.height());
		int oldTextSize = g.getTextSize();
		if (oldTextSize != textSize) {
			g.setTextSize(textSize);
		}
		Typeface oldTypeface = g.getTypeface();
		if (typeface != null) {
			g.setTypeface(typeface);
		}
		g.draw3DString(remain / 1000 + " s", rect.left + rect.width() / 2, rect.top + rect.height() / 2 - 10, Layout.CENTER, 0xFF000000, 0xFFFFFFFF);
		if (oldTextSize != textSize) {
			g.setTextSize(oldTextSize);
		}
		if (typeface != null) {
			g.setTypeface(oldTypeface);
		}
	}
	
	public void update(int timeRemain, int timeLimit) {
		remain = timeRemain;
		this.timeLimit = timeLimit;
	}
	
}
